package com.hbnu.exercise.mysql;

import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseDemo06
{
    public static void main(String[] args)
    {
        Connection connection = null;
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/class2210?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String user = "root";
            String pwd = "123456";

            connection = DriverManager.getConnection(url, user, pwd);

            connection.setAutoCommit(false);

            String sql1 = "UPDATE tb_user SET salary = salary - ? WHERE username = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql1);

            preparedStatement.setDouble(1, 1000.00);
            preparedStatement.setString(2, "赵六");
            preparedStatement.executeUpdate();

            String sql2 = "UPDATE tb_user SET salary = salary + ? WHERE username = ?";
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setDouble(1, 1000.00);
            preparedStatement.setString(2, "王五");
            preparedStatement.executeUpdate();

            connection.setAutoCommit(true);

            preparedStatement.close();
            connection.close();
        } catch (Exception e)
        {
            e.printStackTrace();
            if (connection != null)
            {
                try
                {
                    connection.rollback();
                } catch (SQLException ex)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
